/*
 * Copyleft 2012 Power by Colen.
 *
 * Project: app-crm
 * Date: Apr 22, 2012
 */
package com.crm.common.dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.app.platform.base.dao.DaoSupportEx;
import com.crm.common.exception.CrmSysException;

/**
 * Common DAO Extends
 *
 * @author Colen
 *
 */
public class CommonDaoEx extends DaoSupportEx implements NamingDaoSupport {

    @Override
    public List<Map<String, Object>> namingQueryForList(String sqlId, Map<String, Object> args) {
        Map<String, Object> params = extractValidParams(args);
        String bindedSql = getSql(sqlId, params);
        return queryForList(bindedSql, params);
    }

    private static Map<String, Object> extractValidParams(Map<String, Object> args) {
        Map<String, Object> params = new HashMap<String, Object>();
        if (args == null || args.isEmpty()) {
            return params;
        }

        Object value = null;
        for (Map.Entry<String, Object> e : args.entrySet()) {
            value = e.getValue();
            if (value == null) {
                continue;
            }
            if (value instanceof String && "".equals(value.toString().trim())) {
                continue;
            }
            params.put(e.getKey(), value);
        }
        return params;
    }

    @Override
    public int namingUpdate(String sqlId, Map<String, Object> args) {
        Map<String, Object> params = extractValidParams(args);
        return update(getSql(sqlId, params), params);
    }

    /**
     * get naming-SQL
     *
     * @param sqlId SQL-ID
     * @param params Parameters
     * @return SQL
     */
    private String getSql(String sqlId, Map<String, Object> params) {
        NamingSql nmSql = (NamingSql) NamingSqlFactory.getNamingSql(sqlId);
        if (nmSql == null) {
            throw new CrmSysException("Can not find SQL by ID (" + sqlId +")");
        }
        return nmSql.getBindedSql(params);
    }
}
